package io.github.iogogogo.hippo;

import cn.smallbun.screw.core.Configuration;
import cn.smallbun.screw.core.engine.EngineConfig;
import cn.smallbun.screw.core.engine.EngineFileType;
import cn.smallbun.screw.core.engine.EngineTemplateType;
import cn.smallbun.screw.core.execute.DocumentationExecute;
import cn.smallbun.screw.core.process.ProcessConfig;
import cn.smallbun.screw.core.util.CollectionUtils;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.github.iogogogo.hippo.domain.HippoConf;
import io.github.iogogogo.hippo.util.JsonParse;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by tao.zeng on 2021/11/9.
 */
public class HippoApp {

    private final static Logger LOGGER = LoggerFactory.getLogger(HippoApp.class);

    public static void main(String[] args) throws IOException {
        InputStream inputStream;
        if (args.length == 0) {
            inputStream = HippoApp.class.getClassLoader().getResourceAsStream("application.json");
        } else {
            inputStream = Files.newInputStream(Paths.get(args[0]).toFile().toPath());
        }

        if (Objects.isNull(inputStream)) throw new NullPointerException("配置文件不能为空");

        String result = new BufferedReader(new InputStreamReader(inputStream))
                .lines().collect(Collectors.joining(System.lineSeparator()));

        HippoConf hippoConf = JsonParse.parse(result, HippoConf.class);

        LOGGER.info("\n{}",
                JsonParse.toJson(hippoConf, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty));

        new HippoApp().documentGeneration(hippoConf);
    }

    /**
     * 文档生成
     */
    private void documentGeneration(HippoConf hippoConf) {
        // 数据源
        HikariConfig hikariConfig = hikariConfig(hippoConf);
        try (HikariDataSource dataSource = new HikariDataSource(hikariConfig)) {
            HippoConf.Output output = hippoConf.getOutput();

            List<String> type = output.getType();
            if (CollectionUtils.isNotEmpty(type)) {
                for (String t : type) {
                    build(dataSource, convertType(t), output, hippoConf);
                }
            }
        }
    }

    private static HikariConfig hikariConfig(HippoConf hippoConf) {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(hippoConf.getDriver());
        hikariConfig.setJdbcUrl(hippoConf.getJdbcUrl());
        hikariConfig.setUsername(hippoConf.getUsername());
        hikariConfig.setPassword(hippoConf.getPassword());
        // 设置可以获取tables remarks信息
        hikariConfig.addDataSourceProperty("useInformationSchema", "true");
        hikariConfig.setMinimumIdle(2);
        hikariConfig.setMaximumPoolSize(5);
        hikariConfig.setPoolName("hippo datasource");
        return hikariConfig;
    }

    private EngineFileType convertType(String type) {
        switch (type) {
            case "html":
                return EngineFileType.HTML;
            case "word":
                return EngineFileType.WORD;
            case "md":
                return EngineFileType.MD;
            default:
                throw new RuntimeException(String.join("", "EngineFileType failure, unknown type ", type));
        }
    }

    private void build(DataSource dataSource, EngineFileType fileType, HippoConf.Output output, HippoConf hippoConf) {
        // 生成配置
        EngineConfig engineConfig = EngineConfig.builder()
                // 生成文件路径
                .fileOutputDir(output.getPath())
                // 打开目录
                .openOutputDir(true)
                // 文件类型
                .fileType(fileType)
                // 生成模板实现
                .produceType(EngineTemplateType.freemarker)
                // 自定义文件名称
                .fileName(output.getName()).build();

        HippoConf.DBConfig dbConfig = hippoConf.getDbConfig();
        // 忽略表
        List<String> ignoreTableName = dbConfig.getIgnoreTable();

        // 忽略表前缀
        List<String> ignorePrefix = dbConfig.getIgnorePrefix();

        // 忽略表后缀
        List<String> ignoreSuffix = dbConfig.getIgnoreSuffix();

        ProcessConfig processConfig = ProcessConfig.builder()
                // 指定生成逻辑、当存在指定表、指定表前缀、指定表后缀时，将生成指定表，其余表不生成、并跳过忽略表配置
                // 根据名称指定表生成
                .designatedTableName(new ArrayList<>())
                // 根据表前缀生成
                .designatedTablePrefix(new ArrayList<>())
                // 根据表后缀生成
                .designatedTableSuffix(new ArrayList<>())
                // 忽略表名
                .ignoreTableName(ignoreTableName)
                // 忽略表前缀
                .ignoreTablePrefix(ignorePrefix)
                // 忽略表后缀
                .ignoreTableSuffix(ignoreSuffix).build();

        HippoConf.Hippo hippo = hippoConf.getHippo();

        // 配置
        Configuration config = Configuration.builder()
                // 版本
                .version(hippo.getVersion())
                // 描述
                .description(hippo.getDescription())
                // 数据源
                .dataSource(dataSource)
                // 生成配置
                .engineConfig(engineConfig)
                // 生成配置
                .produceConfig(processConfig)
                .build();
        // 执行生成
        new DocumentationExecute(config).execute();
    }
}
